#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

using namespace std;

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
};

const int backlog = 10;
class Sock
{
public:
    Sock()
        : _sockfd(-1)
    {}
    ~Sock()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

public:
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {    
            lg(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(SocketErr);
        }
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);

        if (bind(_sockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, %s: %d", strerror(errno), errno);
            exit(BindErr);
        }
    }

    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "listen error, %s: %d", strerror(errno), errno);
            exit(ListenErr);
        }
    }

    int Accept(string* peerip, uint16_t* peerport)  //获取客户端的IP和端口号
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        
        int accsock = accept(_sockfd, (struct sockaddr*)&peer, &len);
        if (accsock < 0)
        { 
            lg(Warning, "accept error, %s: %d", strerror(errno), errno);
            return -1;
        }

        char buf[32] = {0};
        inet_ntop(AF_INET, &(peer.sin_addr), buf, sizeof(buf));
        *peerip = buf;
        *peerport = ntohs(peer.sin_port);

        return accsock;
    }

   bool Connect(const std::string &ip, const uint16_t &port)
   {
       struct sockaddr_in remote;
       remote.sin_family = AF_INET;
       remote.sin_addr.s_addr = inet_addr(ip.c_str());
       remote.sin_port = htons(port);

       if (connect(_sockfd, (struct sockaddr*)&remote, sizeof(remote)) < 0)
       {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
       }

       return true;
   }

    int GetFd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};
